// stores/permission.js
import { defineStore } from 'pinia'
import { authRoutes } from '@/router/routes'

export const usePermissionStore = defineStore('permission', {
  state: () => ({
    routes: [],
    isReady: false // 新增路由就绪状态
  }),

  actions: {
    async generateRoutes(roles) {
      try {
        // 添加角色参数处理
        const filteredRoutes = filterAsyncRoutes(authRoutes, roles)
        this.routes = filteredRoutes
        this.isReady = true
      } catch (error) {
        console.error('路由生成失败:', error)
      }
    }
  }
})

// 实现具体的过滤逻辑
const filterRoutes = (routes) => {
  console.log('原始路由:', routes)
  const filtered = routes.filter(route => {
    const hasValidComponent = !!route.component
    const hasVisibleChildren = route.children?.some(child => !child.meta?.hidden)
    const isVisible = !route.meta?.hidden && (hasValidComponent || hasVisibleChildren)
    console.log(`路由 ${route.path} 是否可见:`, isVisible)
    return isVisible
  }).map(route => ({
    ...route,
    path: route.path?.replace(/^\//, '') || '',
    children: route.children ? filterRoutes(route.children) : []
  }))
  console.log('过滤后的路由:', filtered)
  return filtered
}
